'''
版权：Copyright (c) 2019 China

创建日期：Wednesday August 7th 2019
创建者：ymq(ymq) - <<email>>

修改日期: Wednesday, 7th August 2019 11:26:37 am
修改者: ymq(ymq) - <<email>>

说明
 1、基于MongoFilter，针对单据状态过滤，对部分管道操作进行重写，仅适用于对单据管理的表
'''
from server.pao_python.pao.service.data.mongo_db import (AggregationOperators,
                                                         C, F, MongoFilter,
                                                         MongoService, N,
                                                         as_date)


class MongoBillFilter(MongoFilter):
    '''MongoDB 单据管理表 过滤器'''
    ao = AggregationOperators()

    def __init__(self):
        self.filter_objects = []

    def lookup_bill(self, join_collection, local_field, foreign_field, new_colname):
        '''左连接 左连接的表名、原字段名、关联表字段名、新字段名'''
        self.filter_objects.append(
            {'$lookup':  {'from': join_collection, 'localField': local_field, 'foreignField': foreign_field, 'as': 'tep1_colname'}})
        self.filter_objects.append({'$addFields': {new_colname: self.ao.array_filter(
            '$tep1_colname', 'tep2_colname', (F('$tep2_colname.bill_status') == 'valid').f)}})
        self.project({'tep1_colname': 0})
        return self

    def match_bill(self, condition=N()):
        self.match(C('bill_status') == 'valid')
        self.match(condition)
        return self

    def inner_join_bill(self, join_collection, local_field, foreign_field, new_colname):
        self.inner_join(join_collection, local_field, foreign_field, new_colname)
        self.match(C(new_colname+'.bill_status') == 'valid')
        return self

    def graph_lookup_bill(self,join_collection,start_with,connect_from_field,connect_to_field,new_colname,max_depth=None,depth_field=None,condition=None):
        if condition == None :
            self.graph_lookup(join_collection,start_with,connect_from_field,connect_to_field,new_colname,max_depth,depth_field,{'bill_status':'valid'})
        else :
            self.graph_lookup(join_collection,start_with,connect_from_field,connect_to_field,new_colname,max_depth,depth_field,condition)
        return self
